package cn.tedu._05mvcboot03.controller;


import cn.tedu._05mvcboot03.base.response.JsonResult;
import cn.tedu._05mvcboot03.base.response.StatusCode;
import cn.tedu._05mvcboot03.mapper.ArticleMapper;
import cn.tedu._05mvcboot03.mapper.UserMapper;
import cn.tedu._05mvcboot03.pojo.dto.UserArticleDTO;
import cn.tedu._05mvcboot03.pojo.dto.UserLoginDTO;
import cn.tedu._05mvcboot03.pojo.dto.UserRegDTO;
import cn.tedu._05mvcboot03.pojo.entity.Article;
import cn.tedu._05mvcboot03.pojo.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("v1/users/")
@Api(tags = "用户")
@Validated
public class UserController {
    @Autowired(required = false)
    private UserMapper  userMapper;
    @Autowired(required = false)
    private ArticleMapper articleMapper;



    @PostMapping("login")
    @ApiOperation(value = "登录")
    public JsonResult login(@RequestBody UserLoginDTO loginDTO, @ApiIgnore HttpSession session){
        UserVO userVO=userMapper.selectUser(loginDTO);
        if (userVO==null)
            return new JsonResult(StatusCode.USERNAME_PASSWORD_ERROR);
        session.setAttribute("user",userVO);
        return JsonResult.ok();
    }

    @PostMapping("reg")
    @ApiOperation(value = "注册")
    public JsonResult reg(@RequestBody UserRegDTO userRegDTO){
        Integer i=userMapper.selectUserByUsername(userRegDTO.getUsername());
        if (i==null){
            int i1 = userMapper.insertUser(userRegDTO);
            if (i1==1)
                return JsonResult.ok();
        }
        return new JsonResult(StatusCode.USERNAME_EXIT);
    }



    @PostMapping("article")
    @ApiOperation(value = "发布文章")
    public JsonResult insertArticle(@RequestBody @Validated UserArticleDTO userArticleDTO, @ApiIgnore HttpSession session){
        UserVO userVO=(UserVO) session.getAttribute("user");
        Article article=new Article();
        BeanUtils.copyProperties(userArticleDTO,article);
        article.setUserId(userVO.getId());
        int i = articleMapper.insertArticle(article);
        if (i==1)
            return JsonResult.ok();
        return JsonResult.notok();
    }

    @GetMapping("selectByArticleId")
    @ApiOperation(value = "获取文章详细信息")
    public JsonResult selectArticleById(@Range(min = 1,max = 100,message = "文章id要求在1-100之间") @RequestParam Long id){
        return JsonResult.ok(articleMapper.selectArticleById(id));
    }




}
